#!/bin/bash

# SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd.
#
# SPDX-License-Identifier: GPL-3.0-or-later

start_time=$(date "+%Y-%m-%d %H:%M:%S.%3N")
echo -e "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> started mounting dlnfs at [${start_time}]"
echo "dfm_INFO: user: $USER, uid: `id -u`, home: $HOME"

query_dconfig="dde-dconfig --get -a org.deepin.dde.file-manager -r org.deepin.dde.file-manager -k "
# obtain the config of dlnfs mount enable 
dlnfs_enable=`$query_dconfig dfm.mount.dlnfs`
echo "dfm_INFO: dlnfs mount status: $dlnfs_enable"

if [ "$dlnfs_enable" == "true" ]; then
    default_paths=`$query_dconfig dfm.mount.dlnfs.defaults`
    echo "dfm_INFO: default mount paths: $default_paths"

    formats='"[ " ]'
    for path in $default_paths
    do
        contains=$(echo $formats | grep -F "${path}")
        if [ "$contains" != "" ]; then
            continue
        fi

        # remove quotes and commas
        path=${path//'"'/}
        path=${path//','/}
        abs_path=$path

        env_path=`echo $path | grep -o '\$[^/]*'` # env_path = $HOME

        if [ "$env_path" != "" ]; then
            env_var=${env_path//'$'/}  # env_var = HOME
            abs_env_path=`echo ${!env_var}` # abs_env_path = /home/$USER
            abs_path=${path/$env_path/$abs_env_path}  #path = /home/xxxx/xxxx
        fi

        echo "dfm_INFO: ========================= $path [$abs_path]"
        if [ ! -d $abs_path ]; then
            echo "dfm_WARNING: $abs_path do not exist"
            continue
        fi

        # do dlnfs mount for $abs_path.
        gdbus call -y \
            -d org.deepin.dlnfs.Control \
            -o /org/deepin/dlnfs/Control \
            -m org.deepin.dlnfs.Control.Mount \
            "${abs_path}" \
            "{'fsType': <'dlnfs'>}" \
            -t 1

        step_time=$(date "+%Y-%m-%d %H:%M:%S.%3N")
        echo -e "dfm_INFO: finished mount ${path} at [${step_time}]\n"
    done
fi

end_time=$(date "+%Y-%m-%d %H:%M:%S.%3N")
echo -e "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< finished mounting dlnfs at [${end_time}]\n"
